package com.hzy.api;


import com.hzy.common.handler.CrosHandler;
import com.hzy.common.handler.FailureHandler;
import com.hzy.common.handler.RequestParamsHandler;
import com.hzy.common.handler.ResponsePreHandler;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.ResponseContentTypeHandler;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.handler.TimeoutHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 主 HTTP 服务器 Verticle，负责设置 HTTP 服务器和挂载其他 API Verticle 的路由。
 */
public class HttpServerVerticle extends AbstractVerticle {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpServerVerticle.class);

    @Override
    public void start(Promise<Void> startPromise) {
        JsonObject config = (JsonObject) vertx.sharedData().getLocalMap("config").get("appConfig");
        int httpPort = config.getInteger("http.port", 8080);

        Router mainRouter = Router.router(vertx);

        mainRouter.route().handler(new CrosHandler());
        mainRouter.route().handler(BodyHandler.create());
        mainRouter.route().handler(TimeoutHandler.create(10000L));
        mainRouter.route().handler(new RequestParamsHandler());
        mainRouter.route().handler(ResponseContentTypeHandler.create());
        mainRouter.route().handler(new ResponsePreHandler());

        mainRouter.route("/static/*").handler(StaticHandler.create());

        // 挂载各个 API 模块的子路由
        mainRouter.mountSubRouter("/api/ollama", OllamaApiVerticle.createRouter(vertx));
        mainRouter.mountSubRouter("/api/rag", RagApiVerticle.createRouter(vertx));
        mainRouter.mountSubRouter("/api/documents", DocumentApiVerticle.createRouter(vertx));

        // 统一错误处理
        mainRouter.route().failureHandler(new FailureHandler());

        vertx.createHttpServer()
                .requestHandler(mainRouter)
                .listen(httpPort)
                .onSuccess(server -> {
                    LOGGER.info("HTTP server started on port {}", server.actualPort());
                    startPromise.complete();
                })
                .onFailure(throwable -> {
                    LOGGER.error("Failed to start HTTP server", throwable);
                    startPromise.fail(throwable);
                });
    }

}